<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false">
      </el-alert>
      <!-- 步骤条区域 -->
      <el-steps :space="400" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeTabLeave">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="addForm.goodsName"></el-input>
            </el-form-item>
            <el-form-item label="商品价格(元)" prop="goodsPrice">
              <el-input v-model="addForm.goodsPrice" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量(g)" prop="goodsWeight">
              <el-input v-model="addForm.goodsWeight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goodsNumber">
              <el-input v-model="addForm.goodsNumber" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="productCategoryId">
<!--              <el-cascader expand-trigger="hover" :options="catelist" :props="cateProps" v-model="addForm.productCategoryId" @change="handleChange">-->
<!--              </el-cascader>-->
              <el-select v-model="addForm.productCategoryId" clearable placeholder="商品分类信息 必选" style="width: 100%">
                <el-option
                  v-for="item in categorylist"
                  :key="item.productCategoryId"
                  :label="item.productCategoryName"
                  :value="item.productCategoryId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="1">
            <!-- action 表示图片要上传到的后台API地址 -->
            <el-upload
              action="http://localhost:8088/uploadpacture"
              list-type="picture-card"
              :on-success="shopMainIdentityImgSuccess"
              :on-preview="handlePictureCardPreview"
              :headers="headerObj"
              :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="2">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goodsIntroduce" style="min-height: 400px"></quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
  data () {
    return {
      queryInfo: {
        // 当前的页数
        pageNum: 1,
        pageSize: 100
      },
      // 控制图片放大
      dialogVisible: false,
      // 保存上传成功后的图片名称
      dialogImageUrl: '',
      // 存放图片名称的字符串
      imageUrl: '',
      pictureData: '',
      activeIndex: '0',
      // 接收商品分类信息
      categorylist: [],
      // 添加商品的表单数据对象
      addForm: {
        goodsName: '',
        goodsPrice: 0,
        goodsWeight: 0,
        goodsNumber: 0,
        // 商品所属的分类数组
        productCategoryId: '',
        // 图片的数组
        pics: [],
        // 商品的详情描述
        goodsIntroduce: '',
        attrs: [],
        // 照片名称字符串
        imageUrl: '',
        //  获取商品分类列表的参数对象
        // 当前的页数
        pageNum: 1,
        pageSize: 100
      },
      addFormRules: {
        goodsName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goodsPrice: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goodsWeight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goodsNumber: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        productCategoryId: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      // 商品分类列表
      catelist: [],
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 图片上传组件的headers请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      previewPath: '',
      previewVisible: false
    }
  },
  created () {
    this.getshopcategoryList()
  },
  methods: {
    handleRemove (file, fileList) {
      this.addForm.imageUrl = this.addForm.imageUrl.replace(',' + file.response.data, '')
      console.log(this.addForm.imageUrl)
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    shopMainIdentityImgSuccess (res, file) {
      this.dialogImageUrl = URL.createObjectURL(file.raw)
      if (res.status === 200) {
        // 字符串保存
        this.addForm.imageUrl = this.addForm.imageUrl + ',' + (res.data)
      }
    },
    // 级联选择器选中项变化，会触发这个函数
    handleChange () {
    },
    beforeTabLeave (activeName, oldActiveName) {
      // console.log('即将离开的标签页名字是：' + oldActiveName)
      // console.log('即将进入的标签页名字是：' + activeName)
      // return false
      if (oldActiveName === '0' && this.addForm.productCategoryId === '') {
        this.$message.error('请先选择商品分类！')
        return false
      }
    },
    // 添加商品
    add () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项！')
        }
        // 执行添加的业务逻辑
        // lodash   cloneDeep(obj)
        const form = _.cloneDeep(this.addForm)
        console.log('1111111')
        console.log(this.addForm)
        console.log(form)
        form.attrs = this.addForm.attrs
        console.log(form)
        // 发起请求添加商品
        // 商品的名称，必须是唯一的
        console.log(form)
        const { data: res } = await this.$http.post('insertgoods', form)
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败！')
        }

        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      })
    },
    async getshopcategoryList () {
      const { data: res } = await this.$http.get('getproductcategorys', { params: this.queryInfo })
      if (res.status !== 200) {
        return this.$message.error('获取商品分类列表失败！')
      }
      this.categorylist = res.data.list
    }
  },
  computed: {
    cateId () {
      if (this.addForm.productCategoryId.length === 3) {
        return this.addForm.productCategoryId[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .el-checkbox {
    margin: 0 10px 0 0 !important;
  }

  .previewImg {
    width: 100%;
  }

  .btnAdd {
    margin-top: 15px;
  }
</style>
